// 子窗口组件
import { Button } from "antd";
import { useEffect, useState, useRef } from "react";
// 子窗口组件：支持与多个父窗口实例通信
// 子窗口组件：通信管理与状态反馈
const CommunicateTab = () => {
  const [windowId, setWindowId] = useState(null);
  const [messages, setMessages] = useState([]);
  const isMounted = useRef(true);

  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
      // 组件卸载时通知父窗口
      if (window.opener && windowId) {
        window.opener.postMessage(
          { type: 'CHILD_CLOSED', data: { windowId } },
          '*'
        );
      }
    };
  }, [windowId]);

  // 发送消息给父窗口
  const sendToParent = (data) => {
    if (window.opener && windowId && isMounted.current) {
      window.opener.postMessage(
        { 
          type: 'CHILD_RESPONSE', 
          data: { ...data, windowId } 
        },
        '*'
      );
      addMessage('response', data);
    }
  };

  // 添加消息记录
  const addMessage = (type, content) => {
    setMessages(prev => [...prev, {
      type,
      content,
      time: new Date()
    }]);
  };

  // 接收父窗口消息
  useEffect(() => {
    const handleMessage = (e) => {
      if (!isMounted.current) return;
      
      const { type, data } = e.data;
      const { windowId: receivedWindowId } = data || {};
      
      if (type === 'INIT_WINDOW' && receivedWindowId !== undefined) {
        setWindowId(receivedWindowId);
        addMessage('init', {
          message: `接收到初始化消息 (窗口ID: ${receivedWindowId})`,
          data: data
        });
        
        // 子窗口初始化完成，通知父窗口
        window.opener.postMessage(
          { type: 'CHILD_INITIALIZED', data: { windowId: receivedWindowId } },
          '*'
        );
      } else if (type === 'PARENT_COMMAND' && receivedWindowId === windowId) {
        addMessage('command', {
          message: `接收到父窗口命令`,
          command: data.command,
          windowId: receivedWindowId
        });
        console.log(`子窗口 ${receivedWindowId} 接收到命令:`, data.command);
        
        // if (data.command === 'refreshData') {
        //   sendToParent({ 
        //     status: 'refreshed', 
        //     data: { timestamp: new Date().getTime() }
        //   });
        // }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, [windowId]);

  return (
    <div>
      <h3>可通信的子标签页 {(windowId) ? `(ID: ${windowId})` : '(未初始化)'} </h3>
      <div style={{ marginTop: 10, padding: 15, border: '1px solid #e8e8e8', borderRadius: 4 }}>
        <h4>通信记录</h4>
        {messages.length > 0 ? (
          <ul>
            {messages.map((msg, index) => (
              <li key={index}>
                {msg.type === 'init' ? 
                  `初始化: ${msg.content.message}` : 
                  msg.type === 'command' ? 
                    `命令: ${msg.content.command} (时间: ${msg.time.toLocaleTimeString()})` :
                    `响应: ${JSON.stringify(msg.content, null, 2)} (时间: ${msg.time.toLocaleTimeString()})`
                }
              </li>
            ))}
          </ul>
        ) : (
          <p>等待接收消息...</p>
        )}
      </div>
      <Button 
        type="primary" 
        onClick={() => sendToParent({ message: '来自子窗口的消息' })}
        disabled={!windowId}
      >
        发送消息给父窗口
      </Button>
    </div>
  );
};
export default CommunicateTab;